package com.itheima.health.filter;

import com.itheima.health.common.ThreadLocalCommon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{

    private static AntPathMatcher antPathMatcher =new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String requestURI = request.getRequestURI();// /pages/main.html
        log.info("被拦截的资源"+requestURI);
        String[] urls = {
                //需放行资源,这里面将pages中有关的/pages/index.html进行单独拦截
                //这样才能保证重定向时能够跳转成功,
                "/member/login.do",
                "/validateCode/send4Login.do",
                "/pages/login.html",
                "/css/**",
                "/fonts/**",
                "/img/**",
                "/plugins/**",
                "/template/**",
                "/member/**"
        };

        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if(match){
                //可以直接放行
                filterChain.doFilter(request,response);
                log.info("被放行的资源"+url);
                return;
            }
        }

        //设置拦截
        //查看是否登陆,是的话放行,不是进行拦截
        log.info("设置登录资源拦截");
        HttpSession session = request.getSession();
        Integer memberId = (Integer) session.getAttribute("member");
        if(null==memberId){
           //未登录状态,进行拦截并重定向到登录页面
            response.sendRedirect("/pages/login.html");
           return;
        }
        filterChain.doFilter(request,response);
        return;

    }
}
